package logic

import (
	"context"
	"fmt"
	"zy/models/cache"
	"zy/models/mysql"

	"zy/zyrpc/internal/svc"
	"zy/zyrpc/zyrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *zyrpc.LoginRequest) (*zyrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	
	if result != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}

	var user mysql.User

	if user.ID == 0 {
		user = mysql.User{
			Mobile:   in.Mobile,
			Password: in.Password,
		}

		mysql.DB.Debug().Create(&user)

	} else {

		if user.Password != in.Password {
			return nil, fmt.Errorf("当前密码错误，请重新输入")
		}

	}

	return &zyrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
